package com.yz.sharkim.websocket;

import com.yz.sharkim.annotation.IdMapping;
import com.yz.sharkim.annotation.WebSocketController;
import com.yz.sharkim.entity.message.BaseMessage;
import com.yz.sharkim.entity.User;
import com.yz.sharkim.entity.message.request.HeartBeat;
import com.yz.sharkim.entity.message.request.Send;
import com.yz.sharkim.entity.message.response.CommonResponse;
import com.yz.sharkim.entity.message.response.Receive;
import com.yz.sharkim.service.IUserService;
import com.yz.sharkim.util.ConvertUtil;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import lombok.val;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * @author yangzheng
 * @version 1.0
 * @date 2019/11/4 9:22
 */
@WebSocketController
public class MessageController {

    @Autowired
    private IUserService userService;

    @IdMapping(BaseMessage.HEART_BEAT)
    public BaseMessage heartBeat(HeartBeat message) {
        return new CommonResponse();
    }

    @IdMapping(BaseMessage.SEND_MESSAGE)
    public BaseMessage sendMessage(Send message, User current) {
        val user = userService.getUserById(message.getTo());
        if (user != null) {
            user.getChannel().writeAndFlush(
                   new TextWebSocketFrame(ConvertUtil.toJson(new Receive(current.getId(), message.getContent(), message.getTime())))
            );
        }
        return new CommonResponse();
    }
}
